const { Op } = require("sequelize");

const seq = require('../db/seq');
const Address = require('../model/address');

const address = Address(seq);

class AddressController {
    //添加地址
    async addAddress(ctx, next) {
        try {
            const user_id = ctx.state.user.user_id;
            const { address_info, user_tel, default_address } = ctx.request.body;
            console.log(address_info);
            const res = await address.create({ user_id: user_id, address_info: address_info, user_tel: user_tel, default_address: default_address });
            ctx.body = {
                code: 0,
                message: '添加地址成功',
                result: res
            }
        } catch (err) {
            console.log('添加地址失败', err);
            return ctx.body = {
                error: '添加地址失败',
                result: err
            }
        }

    }

    //更新地址
    async updateAddress(ctx, next) {
        const user_id = ctx.state.user.user_id;
        const { address_id, ...info } = ctx.request.body;
        try {
            const res = await address.update(info, { where: { address_id: address_id } });
            ctx.body = {
                code: 0,
                message: '更新地址成功'
            }
        } catch {
            console.log('删除购物车失败');
            return ctx.body = {
                error: '删除购物车失败'
            }
        }

    }

    //删除地址
    async deleteAddress(ctx, next) {
        const { ids } = ctx.request.body;
        try {
            const res = address.destroy({
                where: {
                    address_id: {
                        [Op.in]: ids,
                    }
                }
            })
            ctx.body = {
                code: 0,
                message: '删除地址成功',
                result: res
            }
        } catch (err) {
            console.log('删除地址失败', err);
            return ctx.body = {
                error: '删除地址失败'
            }
        }
    }
}

module.exports = new AddressController();